<template>
  <div>
    <el-card>
      <template #header>
        <h2>外出登记</h2>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="searchForm" inline>
        <el-form-item>
          <el-input
            v-model="searchForm.name"
            placeholder="客户姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="searchData">查询</el-button>
        </el-form-item>
      </el-form>

      <div class="table-title">
        <h3>客户信息</h3>
      </div>

      <!-- 表格区域 -->
      <el-table :data="tableData" border stripe style="width: 100%;">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="customerName" label="客户姓名" width="100" />
        <el-table-column prop="reason" label="外出事由" />
        <el-table-column
          prop="outTime"
          label="外出时间"
          :formatter="formatDate"
          width="140"
        />
        <el-table-column
          prop="expectedReturn"
          label="预计回院时间"
          :formatter="formatDate"
          width="140"
        />
        <el-table-column
          prop="actualReturn"
          label="实际回院时间"
          :formatter="formatDate"
          width="140"
        />
        <el-table-column prop="companionName" label="陪同人" width="100" />
        <el-table-column
          prop="companionRelation"
          label="与老人关系"
          width="120"
        />
        <el-table-column
          prop="companionPhone"
          label="陪同人电话"
          width="140"
        />
        <el-table-column label="审批状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.approveStatus)"
              effect="dark"
            >
              {{ getStatusLabel(row.approveStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operatorUserName" label="审批人姓名" width="120" />
        <el-table-column
          prop="approveTime"
          label="审批时间"
          :formatter="formatDate"
          width="140"
        />
		<el-table-column fixed="right" label="操作" width="160">
		  <template #default="{ row }">
			<el-button type="danger" size="small" @click="approve(row)">
			  {{ row.approveStatus === 0 ? '审批' : '重审' }}
			</el-button>
			<el-button type="primary" size="small" @click="edit(row)">修改申请</el-button>
		  </template>
		</el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="loadData"
        @size-change="loadData"
      />
    </el-card>

    <!-- 抽屉表单 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="40%">
      <el-form :model="formData" label-width="100px">
		   <!-- 隐藏的 id 字段，编辑时会被赋值，新增时可以留空 -->
		    <el-form-item style="display: none;">
		      <el-input v-model="formData.id" />
		    </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="formData.customerName" />
        </el-form-item>
        <el-form-item label="外出事由">
          <el-input v-model="formData.reason" />
        </el-form-item>
        <el-form-item label="外出时间">
          <el-date-picker v-model="formData.outTime" type="date" />
        </el-form-item>
        <el-form-item label="预计回院时间">
          <el-date-picker v-model="formData.expectedReturn" type="date" />
        </el-form-item>
        <el-form-item label="实际回院时间">
          <el-date-picker v-model="formData.actualReturn" type="date" />
        </el-form-item>
        <el-form-item label="陪同人">
          <el-input v-model="formData.companionName" />
        </el-form-item>
        <el-form-item label="与老人关系">
          <el-input v-model="formData.companionRelation" />
        </el-form-item>
        <el-form-item label="陪同人电话">
          <el-input v-model="formData.companionPhone" />
        </el-form-item>
        <el-form-item label="审批状态">
          <el-radio-group v-model="formData.approveStatus">
            <el-radio :value="0">已提交</el-radio>
            <el-radio :value="1">同意</el-radio>
            <el-radio :value="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批人ID">
          <el-input v-model="formData.operatorUserId" />
        </el-form-item>
        <el-form-item label="审批时间">
          <el-date-picker v-model="formData.approveTime" type="date" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">{{ drawerTitle }}</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import { reactive, ref, watch, inject } from 'vue';
import dayjs from 'dayjs';
import { ElMessage,ElMessageBox } from 'element-plus';
import qs from 'qs'
import { jwtDecode } from 'jwt-decode'

// 注入 axios
const axios = inject('axios');

// 抽屉状态与标题
const drawerVisible = ref(false);
const drawerTitle = ref('外出登记');

const getStatusLabel = (status) => {
  switch (status) {
    case 0: return '待审批';
    case 1: return '已通过';
    case 2: return '已拒绝';
    default: return '未知';
  }
};

const getStatusType = (status) => {
  switch (status) {
    case 0: return 'warning'; // 待审批 - 黄色
    case 1: return 'success'; // 已通过 - 绿色
    case 2: return 'danger';  // 已拒绝 - 红色
    default: return 'info';   // 默认蓝灰
  }
};

// 表单与搜索模型
const formData = reactive({
  id: 0,
  customerId: null,
  customerName:'',
  reason: '',
  outTime: '',
  expectedReturn: '',
  actualReturn: '',
  companionName: '',
  companionRelation: null,
  companionPhone: '',
  approveStatus: 0,
  operatorUserId: null,
  approveTime: ''
});
const searchForm = reactive({ name: '' });

// 表格与分页
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const opId=ref('')

// 加载列表
const loadData = () => {
  axios.post('OutRegistrationController/queryAll',qs.stringify({
    cur: currentPage.value,
    number: pageSize.value,
    name: searchForm.name
  })).then(res => {
    const rb = res.data;
    if (rb.status === 200) {
      tableData.value = rb.data;
      total.value = rb.total;
    } else {
      ElMessage.error('加载失败: ' + rb.message);
    }
  });
};
watch([currentPage, pageSize], loadData);
loadData();

// 格式化日期
const formatDate = (row, col, val) => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '';

// 查询
const searchData = () => { currentPage.value = 1; loadData(); };

// 打开抽屉
const openDrawer = () => {
  Object.assign(formData, {
    id: 0,
    customerId: null,
    reason: '',
    outTime: '',
    expectedReturn: '',
    actualReturn: '',
    companionName: '',
    companionRelation: null,
    companionPhone: '',
    approveStatus: 0,
    operatorUserId: null,
    approveTime: ''
  });
  drawerTitle.value = '外出登记';
  drawerVisible.value = true;
};

// 编辑
const edit = (row) => {
  Object.assign(formData, row);
  drawerTitle.value = '修改外出';
  drawerVisible.value = true;
};

// 审批
const approve = (row) => {
  ElMessageBox({
    title: '审批确认',
    message: '请确认是否同意该申请？',
    showCancelButton: true,
    showConfirmButton: true,
    confirmButtonText: '同意',
    cancelButtonText: '拒绝',
    type: 'warning',
	distinguishCancelAndClose: true
  }).then(() => {
    // 用户点击“同意”
    sendApproveRequest(row.id, 1); // 1 = 同意
  }).catch((action) => {
	   if (action === 'cancel') {
	      // 点了“拒绝”按钮
	      sendApproveRequest(row.id, 2);
	    } else {
	      // 点了“关闭”或按了ESC，不做任何处理
	      ElMessage.info('已取消审批');
	    }
  });
};

const sendApproveRequest = (id, status) => {
  axios.post('OutRegistrationController/approve', qs.stringify({
    id,
    approveStatus: status,
    operatorUserId: opId.value // TODO: 换成当前登录用户 ID
  })).then(res => {
    const rb = res.data;
    if (rb.status === 200) {
      ElMessage.success(status === 1 ? '审批通过' : '已拒绝申请');
      loadData();
    } else {
      ElMessage.error('审批失败：' + rb.message);
    }
  });
};

// 提交表单（新增或修改）
const submitForm = () => {
	const payload = { ...formData };
	  // 不提交空的日期字段
	  if (!payload.outTime)         delete payload.outTime;
	  if (!payload.expectedReturn)   delete payload.expectedReturn;
	  if (!payload.actualReturn)     delete payload.actualReturn;
	  if (!payload.approveTime)     delete payload.approveTime;
	
	  // 同样也 delete payload.customerName 等展示字段……
	  delete payload.customerName;
  const url = '/OutRegistrationController/update';
  axios.post(url, qs.stringify(payload)).then(res => {
    const rb = res.data;
    if (rb.status === 200) {
      ElMessage.success(`${drawerTitle.value}成功`);
      drawerVisible.value = false;
      loadData();
    } else {
      ElMessage.error(rb.message);
    }
  });
};

const init = ()=>{
	let token=sessionStorage.getItem('token');
	console.log(token);
	const payload = jwtDecode(token);
	const user = JSON.parse(payload.mobileJson)
	opId.value=user.id;
}

init();
</script>

<style scoped>
.el-pagination { margin-top: 20px; }
.table-title { background: #f5f5f5; padding: 8px; margin: 10px 0; }
</style>
